package com.inhgroup.flashcards.io;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Contains various methods for interacting with Excel spreadsheets.
 * 
 * @author Branden Ogata
 *
 */

public class ExcelUtilities
{
  /**
   * The logger for the ExcelUtilities class.
   * 
   */
  private static Logger logger = LoggerFactory.getLogger(ExcelUtilities.class.getName());  
  
  /**
   * A protected constructor to minimize the possibility of instantiating this class.
   * 
   */
  
  protected ExcelUtilities()
  {
    logger.error("The ExcelUtilities class should not be instantiated");
  }

  /**
   * Returns an array containing the Cell instances in the given Row.
   * 
   * @param row The Row to get cells from.
   * 
   * @return cells The Cell[] containing the cells in the parameter row.
   * 
   */
  
  public static Cell[] getCellsInRow(Row row)
  {
    Cell[] cells = new Cell[ExcelUtilities.getNumberOfCellsInRow(row)];
    
    for (int i = 0; i < cells.length; i++)
    {
      cells[i] = row.getCell(i);
    }
    
    return cells;
  }

  /**
   * Returns the number of rows in the given Sheet.
   * Sheet.getPhysicalNumberOfRows appears to only count rows with data,
   * which causes issues when blank rows are involved.
   * 
   * @param sheet The Sheet in which to count rows.
   * 
   * @return numberOfRows An int equal to the number of rows in the sheet.
   * 
   */
  
  public static int getNumberOfRowsInSheet(Sheet sheet)
  {
    int numberOfRows = 0;
    
    while ((sheet != null) && ((sheet.getRow(numberOfRows) != null) || 
                               (numberOfRows < sheet.getPhysicalNumberOfRows())))
    {
      numberOfRows++;
    }
    
    return numberOfRows;
  }

  /**
   * Returns the number of cells in the given Row.
   * 
   * @param row The Row in which to count cells.
   * 
   * @return numberOfCells An int equal to the number of cells in the sheet.
   * 
   */
  
  public static int getNumberOfCellsInRow(Row row)
  {
    int numberOfCells = 0;
    
    while ((row != null) && ((row.getCell(numberOfCells) != null) || 
                             (numberOfCells < row.getPhysicalNumberOfCells())))
    {
      numberOfCells++;
    }
    
    return numberOfCells;
  }  
}
